package org.barman.servlet;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.barman.dao.ItemDAO;
import org.barman.exception.CustomMessageException;
import org.barman.pojo.Item;

@WebServlet("/ManageItemServlet")
public class ManageItemServlet extends ExceptionHandlingHttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doExceptionHandledPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, CustomMessageException {

		String action = request.getParameter("action");

		String name = request.getParameter("name");
		BigDecimal price = new BigDecimal(request.getParameter("price"));

		if (name == null || "".equals(name)) {
			throw new CustomMessageException("invalid item name");
		}

		if (price == null || "".equals(price)) {
			throw new CustomMessageException("invalid item price");
		}

		Item item = new Item();
		
		
		ItemDAO itemDAO = new ItemDAO();

		if ("add".equals(action)) {
			item.setName(name);
			item.setPrice(price);
			item.setCreated(new Date(System.currentTimeMillis()));
			
			itemDAO.insert(item);
			request.setAttribute("flash.message", "item added successfully");

		} else if ("edit".equals(action)) {
			int itemId = Integer.parseInt(request.getParameter("id"));

			item = itemDAO.get(itemId);
			item.setName(name);
			item.setPrice(price);
			item.setModified(new Date(System.currentTimeMillis()));

			itemDAO.update(item);
			request.setAttribute("flash.message", "item updated successfully");

		}

		response.sendRedirect("admin/main.jsp");
	}
}
